/**
 * 新增工位页面
 */
import React, { useEffect, useState } from 'react';
import { Form, Card, Button, Select, Input, message, Spin } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { BottomAction } from '@/components';
import { Company } from '@/containers';
import { handleAddStation, getUsedStation } from '@/pages/AdminManage/service';
import { getCompanyDetail } from '@/pages/Organization/OrgFlow/services';
import styles from '../index.less';
import { AREA_CODE } from './enum';

const MAX_STATION_NUM = 999;

const FORM_DEFAULT_LAYOUT = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 15
    }
};

const AddStation = ({ form }) => {
    const { getFieldDecorator, setFieldsValue, resetFields, getFieldValue } = form;
    const newUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const [submitLoading, setSubmitLoading] = useState(false);
    const [siteLoading, setSiteLoading] = useState(false);
    const [useAreaLoading, setUseAreaLoading] = useState(false);
    const [siteList, setSiteList] = useState([]);
    const [maxNum, setMaxNum] = useState('000');
    const [upPlan, setUpPlan] = useState([]);
    const [plan, setPlan] = useState([]);
    const [curStationNum] = useState({ data: { begin: undefined, end: undefined } });
    const [validateName, setValidateName] = useState(undefined);
    const [validateStatus, setValidateStatus] = useState(undefined);
    const handleSubmit = async () => {
        form.validateFields(async (err, values) => {
            console.log(values);
            if (!err) {
               try {
                setSubmitLoading(true);
                const { code, msg } = await handleAddStation({
                    ...values
                });
                if (code === 10000) {
                    message.success('新增成功！');
                    pageTabUtil.goBack();
                } else {
                    message.error(msg)
                }
                setSubmitLoading(false);
               } catch (e) {
                setSubmitLoading(false);
               }
            }
        });
    };

    // const getArea = async addCode => {
    //     try {
    //         setAreaList([]);
    //         setAreaLoading(true);
    //         const { data: areaQueryData = {}, code, msg } = await getValidArea(addCode);
    //         if (code === 10000) {
    //             const keys = Object.keys(areaQueryData);
    //             setAreaList(keys);
    //         } else {
    //             message.error(msg)
    //         }
    //         setAreaLoading(false);
    //     } catch (e) {
    //         message.error(e);
    //         setAreaLoading(false);
    //     }
    // };

    const getSiteList = async companyCode => {
        try {
            setSiteLoading(true);
            const { data = {} } = await getCompanyDetail(companyCode);
            setSiteList(data.addressDtoList || []);
            setSiteLoading(false);
            const curCompanyCode = getFieldValue('companyCode');
            const addressCode = data?.addressDtoList?.length ? data.addressDtoList[0].addressCode : undefined;
            resetFields();
            setFieldsValue({
                companyCode: curCompanyCode,
                addressCode
            });
            // await getArea(addressCode)
        } catch (e) {
            console.log(e);
            setSiteLoading(false);
        }
    };

    const getUsedList = async cubicleArea => {
        try {
           setUseAreaLoading(true);
           const { data, code, msg } = await getUsedStation({
               addressCode: getFieldValue('addressCode'),
               cubicleArea
           });
           if (code === 10000) {
               const { end, plannedCodes = [], unPlannedCodes = [] } = data;
               setMaxNum(end || '000');
               setPlan(plannedCodes);
               setUpPlan(unPlannedCodes)
           } else {
               message.error(msg);
           }
            setUseAreaLoading(false);
        } catch (e) {
            message.error(e);
            setUseAreaLoading(false);
        }
    };

    const zero = (value, len = 3) => {
        if (value.length >= len) return value;
        const nLen = len - value.length;
        // eslint-disable-next-line for-direction,no-plusplus
        for (let i = 0; i < nLen; i++) {
            // eslint-disable-next-line no-param-reassign
            value = `0${value}`;
        }
        return value;
    };

    const handleUsedList = data => {
        // debugger;
        // const plan = ['001', '006-019'];
        const { begin, end } = data;
        const rejectArr = [];
        let startIndex = -1;
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < plan.length; i++) {
            const arr = plan[i].split('-');
            if (begin < arr[0]) {
                startIndex = i;
                break;
            }
        }
        if (startIndex > -1) {
            // eslint-disable-next-line no-plusplus
            for (let j = startIndex; j < plan.length; j++) {
                const arr = plan[j].split('-');
                if (end > arr[0]) {
                    rejectArr.push(plan[j]);
                }
            }
        }
        if (rejectArr.length) {
            setValidateName(`已自动剔除中间已规划工位：${rejectArr.join('、')}`);
            setValidateStatus('warning');
        } else {
            setValidateName(undefined);
            setValidateStatus(undefined);
        }
    };

    const handleSetStationNum = ({ value, start, end }) => {
        // const upPlan = ['002', '003', '004', '005'];
        setValidateName(undefined);
        setValidateStatus(undefined);
        const curMax = parseInt(maxNum, 10);
        const num = value || getFieldValue('num');
        // 当前已规划的最大值已达到999,且可用编号不足
        if (curMax === MAX_STATION_NUM && +num > upPlan.length) {
            setTimeout(() => {
                setFieldsValue({
                    num: undefined,
                    begin: undefined,
                    end: undefined
                });
                message.warning(`目前该区域内的工位数量已达上限（${MAX_STATION_NUM}个）`);
            }, 0);
            return;
        }
        // 数量+当前最大工位值超过999
        if (curMax !== MAX_STATION_NUM && +num + curMax > MAX_STATION_NUM) {
            console.log(curStationNum.data);
            setTimeout(() => {
                setFieldsValue({
                    num: undefined,
                    begin: undefined,
                    end: undefined
                });
                // setFieldsValue(curStationNum.data);
            }, 0);
            message.warning(`目前该区域内已创建${curMax}个工位（最多支持创建${MAX_STATION_NUM}个）`);
            return;
        }
        // 默认更改数量
        let curStart = curMax + 1;
        let curEnd = +num + curMax;
        // 更改起始编号
        if (start) {
            const curStartIndex = upPlan.indexOf(start);
            // 填入的编号之后剩余工位数
            const remainUp = upPlan.length - curStartIndex - 1;
            if ((+num + parseInt(start, 10) - 1) > MAX_STATION_NUM) {
                setTimeout(() => {
                    setFieldsValue(curStationNum.data);
                }, 0);
                message.warning(`开始编号${start}之后无足够工位可规划`);
                return;
            }
            // 工位已满999，剩余空位足够分配个数，但是填入的开始编号之后位置不够
            if (curMax === MAX_STATION_NUM && curStartIndex !== -1 && +num - 1 > remainUp) {
                setFieldsValue(curStationNum.data);
                message.warning(`开始编号${start}之后无足够工位可规划`);
                return;
            }
            // 无可用区域，且输入大于等于当前最大座位值
            if (curStartIndex === -1 && start > maxNum) {
                curStart = start;
                curEnd = +num - 1 + parseInt(start, 10)
            }
            // 无可用区域，输入小于当前最大座位值
            if (curStartIndex === -1 && start <= maxNum) {
                message.warning(`${start}为已规划区域`);
                setFieldsValue(curStationNum.data);
                return;
            }
            // 当前座位为剩余可用值,
            if (curStartIndex !== -1) {
                curStart = start;
                if (+num - 1 > remainUp) {
                    curEnd = (+num - 1 - remainUp) + curMax;
                } else {
                    curEnd = upPlan[curStartIndex + +num - 1]
                }
            }
        }
        // 更改结束编号
        if (end) {
            // 当前输入值为已规划区域
            if (end === maxNum || (end < maxNum && upPlan.indexOf(end) === -1)) {
                message.warning(`${end}为已规划区域`);
                setFieldsValue(curStationNum.data);
                return
            }
            // 输入值大于最大工位值
            if (end > maxNum) {
                const remain = upPlan.length + (end - maxNum);
                if (+num > remain) {
                    message.warning(`截止编号${end}之前无足够工位可规划`);
                    setFieldsValue(curStationNum.data);
                    return;
                }
                // 最大工位值之后满足数量
                if (end - maxNum >= +num) {
                    curStart = parseInt(end, 10) - (+num - 1);
                } else {
                    // 最大工位值之后不满足数量，需要到空闲位列表查找
                    const oldLen = +num - (end - maxNum); // 需要从剩余列表中，从后往前找几个
                    curStart = upPlan[upPlan.length - oldLen];
                }
                curEnd = end;
            }
            // 输出值刚好在空闲列表中
            if (end < maxNum) {
                const curIndex = upPlan.indexOf(end);
                if (+num - 1 > curIndex) {
                    message.warning(`截止编号${end}之前无足够工位可规划`);
                    setFieldsValue(curStationNum.data);
                    return;
                }
                curStart = upPlan[curIndex - (+num - 1)];
                curEnd = end;
            }
        }
        // 当前已规划的最大值已达到999,剩余工位足够填充
        if (curMax === MAX_STATION_NUM && !start && !end) {
            // eslint-disable-next-line prefer-destructuring
            curStart = upPlan[0];
            curEnd = upPlan[+num - 1]
        }
        const stationNum = {
            num,
            begin: zero(`${curStart}`),
            end: zero(`${curEnd}`)
        };
        setFieldsValue(stationNum);
        handleUsedList(stationNum);
        curStationNum.data = stationNum;
    };

    useEffect(() => {
        console.log('===========用户信息===========', newUser);
        getSiteList(newUser.administrativeOrganizationCode);
    }, []);
    return (
        <PageHeaderWrapper>
            <Spin spinning={submitLoading}>
                <Card
                    title="新增工位"
                    bordered={false}
                    extra={
                        <BottomAction>
                            <Button onClick={() => pageTabUtil.goBack()} style={{ marginRight: 8 }}>
                                取消
                            </Button>
                            <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                                保存
                            </Button>
                        </BottomAction>
                }
            >
                    <Form
                        {...FORM_DEFAULT_LAYOUT}
                        style={{ width: 600 }}
                        autoComplete="off"
                >
                        <Form.Item label="行政机构" style={{ marginRight: 8 }}>
                            {/* ORG1347011679515189249 */}
                            {getFieldDecorator('companyCode', {
                            initialValue: newUser.administrativeOrganizationCode || undefined,
                            rules: [
                                { required: true, message: '请选择行政机构' }
                            ]
                        })(
                            <Company
                                style={{ width: 375 }}
                                placeholder="请选择行政机构"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                allowClear={false}
                                onChange={val => {
                                    resetFields();
                                    getSiteList(val);
                                }}
                            />
                        )}
                        </Form.Item>
                        <Form.Item label="办公地点" style={{ marginBottom: 16 }}>
                            <Spin spinning={siteLoading}>
                                {getFieldDecorator('addressCode', {
                                initialValue: undefined,
                                rules: [
                                    { required: true, message: '请选择办公地点' }
                                ]
                            })(
                                <Select
                                    placeholder="请选择"
                                    onChange={val => {
                                        const curCompanyCode = getFieldValue('companyCode');
                                        resetFields();
                                        setFieldsValue({
                                            companyCode: curCompanyCode,
                                            addressCode: val
                                        });
                                        // getArea(val);
                                    }}
                                >
                                    {siteList.map(item => (
                                        <Select.Option key={item.addressCode} value={item.addressCode}>
                                            {item.addressName}
                                        </Select.Option>
                                    ))}
                                </Select>
                            )}
                            </Spin>
                        </Form.Item>
                        <Form.Item label="工位区域" style={{ marginBottom: 16 }}>
                            {getFieldDecorator('cubicleArea', {
                            initialValue: undefined,
                            rules: [
                                { required: true, message: '请选择工位区域' }
                            ]
                        })(
                            <Select
                                disabled={!getFieldValue('addressCode') || siteLoading}
                                placeholder="请选择工位区域"
                                onChange={val => {
                                    setMaxNum(undefined);
                                    setFieldsValue({
                                        num: undefined,
                                        begin: undefined,
                                        end: undefined
                                    });
                                    getUsedList(val);
                                }}
                            >
                                {AREA_CODE.map(item => (
                                    <Select.Option key={item.value} value={item.value}>
                                        {item.text}
                                    </Select.Option>
                                ))}
                            </Select>
                        )}
                        </Form.Item>
                        <Form.Item label="新增数量" style={{ marginBottom: 16 }}>
                            {getFieldDecorator('num', {
                            initialValue: undefined,
                            rules: [
                                { required: true, message: '请输入新增数量' }
                            ],
                            getValueFromEvent: e => e.target.value.replace(/^0|[^\d]+/g, '')
                        })(
                            <Input
                                placeholder="请输入"
                                maxLength={3}
                                disabled={!getFieldValue('cubicleArea') || useAreaLoading}
                                onChange={e => {
                                    const { value } = e.target;
                                    curStationNum.data = { begin: undefined, end: undefined };
                                    if (value) {
                                        if (/^0|[^\d]+/g.test(value)) return;
                                        handleSetStationNum({ value });
                                    } else {
                                        setFieldsValue({ begin: undefined, end: undefined })
                                    }
                                }}
                            />
                        )}
                        </Form.Item>
                        <Form.Item label="工位编号" required style={{ marginBottom: 16 }} help={validateName} validateStatus={validateStatus}>
                            <Form.Item
                                style={{ display: 'inline-block', width: 'calc(50% - 12px)', marginBottom: 0 }}
                        >
                                {getFieldDecorator('begin', {
                                initialValue: undefined,
                                rules: [
                                    { required: true, message: '请输入开始编号' }
                                ],
                                getValueFromEvent: e => {
                                    if (e.target.value.length === 3 && parseInt(e.target.value, 10) === 0) return '00';
                                    return e.target.value.replace(/[^\d]+/g, '');
                                }
                            })(
                                <Input
                                    placeholder="自动生成"
                                    disabled={!getFieldValue('cubicleArea') || !getFieldValue('num')}
                                    maxLength={3}
                                    onBlur={e => {
                                        const { value } = e.target;
                                        if (value.length === 3 || (value && parseInt(value, 10) !== 0)) {
                                            handleSetStationNum({ start: zero(value) })
                                        } else {
                                            setFieldsValue(curStationNum.data);
                                        }
                                    }}
                                />
                            )}
                            </Form.Item>
                            <span style={{ display: 'inline-block', width: '24px', textAlign: 'center' }}>-</span>
                            <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 12px)', marginBottom: 0 }}>
                                {getFieldDecorator('end', {
                                initialValue: undefined,
                                rules: [
                                    { required: true, message: '请输入截止编号' }
                                ],
                                getValueFromEvent: e => {
                                    if (e.target.value.length === 3 && parseInt(e.target.value, 10) === 0) return '00';
                                    return e.target.value.replace(/[^\d]+/g, '');
                                }
                            })(
                                <Input
                                    placeholder="自动生成"
                                    disabled={!getFieldValue('cubicleArea') || !getFieldValue('num')}
                                    maxLength={3}
                                    onBlur={e => {
                                        const { value } = e.target;
                                        if (value.length === 3 || (value && parseInt(value, 10) !== 0)) {
                                            handleSetStationNum({ end: zero(value) })
                                        } else {
                                            setFieldsValue(curStationNum.data);
                                        }
                                    }}
                                />
                            )}
                            </Form.Item>
                        </Form.Item>
                        <Form.Item label=" " colon={false} style={{ marginBottom: 16 }}>
                            <Spin spinning={useAreaLoading}>
                                {
                            getFieldValue('cubicleArea') && plan.length
                                ? <div className={styles.checkUsedWrap}>
                                    <div className={styles.title}>{getFieldValue('cubicleArea')}已规划的工位编号：</div>
                                    <ul className={styles.usedList}>
                                        {
                                            plan.map(item => <li key={item}>{item}</li>)
                                        }
                                    </ul>
                                </div>
                                : null
                        }
                            </Spin>
                        </Form.Item>
                    </Form>
                </Card>
            </Spin>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(AddStation);
